const express=require('express');
//创建web服务器
const app=express();
//启动服务器设置监听端口
app.listen(8080,()=>{
	console.log('端口为8080,服务器启动成功');
})

//添加中间件对body数据解码
app.use(express.urlencoded({
	extended: false
}))
//跨域问题的处理
app.all('*', function (req, res, next) {
    //允许的来源
    res.header("Access-Control-Allow-Origin", "*")
    //允许的头部信息，如果自定义请求头，需要添加以下信息，允许列表可以根据需求添加
    res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, Accept-Encoding")
    //允许的请求类型
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
    next()
})
//配置CORS，指定放行的域名，防止出现跨域问题
// const cors = require('cors')
// app.use(cors({
//   origin:"*"
// }))


//配置multer中间件
const multer = require('multer')
obj = multer.diskStorage({
  destination : function(req, file, cb){ //指定目录
    cb(null, 'public/video')
  },
  filename : function (req, file, cb){ // 指定文件名
    let name = file.originalname
    // name:  abcd.jpg    xxxdfdd.zip
    let ext = name.substr(name.lastIndexOf('.'))
    cb(null, uuid.v4() + ext)
  }
})
const uploadTools = multer({
  storage : obj
})
const uuid = require('uuid')
//接收请求
app.post('/upload',
  uploadTools.array('uploadFile'), (req, res)=>{
    console.log(req.files)
    let urls = []
    req.files.forEach(item=>{
      urls.push(`http://localhost:8080/${item.filename}`)
    })
    res.send({code:200, msg:'ok', urls})
})


//托管静态资源
app.use(express.static('./public'));
//引入自定义路由模块
const userRouter = require('./router/user.js');
app.use('/user',userRouter);

const indexRouter = require('./router/course.js');
app.use('/index',indexRouter);

const videoRouter = require('./router/course.js');
app.use('/video',videoRouter);

const shoppingRouter = require('./router/course.js');
app.use('/shopping',shoppingRouter);